package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.EncryptPassword;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.*;
import com.mainbo.modular.system.dao.*;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.excelUser.EduEmployee;
import com.mainbo.modular.system.model.People;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.service.IPtAccountService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mainbo.modular.system.service.IPtResourcesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author moshang
 * @Date 2020-02-17 21:23:57
 */
@Service
public class PtAccountServiceImpl extends ServiceImpl<PtAccountMapper, PtAccount> implements IPtAccountService {
    @Resource
    private PtStudentMapper studentMapper;
    @Resource
    private PtTeacherMapper teacherMapper;
    @Resource
    private PtAccountMapper accountMapper;
    @Resource
    private PtEduEmpMapper eduEmpMapper;
    @Resource
    private PtPeopleMapper peopleMapper;
    @Resource
    private IPtResourcesService resourcesService;
    @Autowired
    private JmsService jmsService;
    @Resource
    private PtUserRoleMapper ptUserRoleMapper;
    @Resource
    private PtRoleMapper ptRoleMapper;

    @Override
    public boolean ExcelCheckStudentCode(String name, String studentCode, String orgId) {
        Student studentModel = new Student();
        studentModel.setStudentCode(studentCode);
        studentModel.setOrgId(orgId);
        Student student = studentMapper.selectOne(studentModel);
        if (StringUtils.isNotBlank(name)) {
            if (null != student && null != student.getName()) {
                if (!name.equals(student.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean ExcelCheckCard(Teacher t, String orgId, Integer userType) {
        Teacher teacherModel = new Teacher();
        teacherModel.setSchoolCard(t.getSchoolCard());
        /*teacherModel.setEnable(true);*/
        Student studentModel = new Student();
        studentModel.setStudentCardId(t.getSchoolCard());
        /*studentModel.setEnable(true);*/
        Teacher teacher = teacherMapper.selectOne(teacherModel);
        Student student = studentMapper.selectOne(studentModel);
        if (StringUtils.isEmpty(t.getName())) {
            if (teacher == null && student == null) {
                return false;
            } else {
                return true;
            }
        } else {
            if (null != teacher) {
                if ((!t.getName().equals(teacher.getName()))) {
                    return true;
                } else if (t.getName().equals(teacher.getName()) && !orgId.equals(teacher.getOrgId()) && userType != PtAccount.TEACHER_USER) {
                    return true;
                } else {
                    return false;
                }
            } else if (null != student) {
                if ((!t.getName().equals(student.getName()))) {
                    return true;
                } else if (t.getName().equals(student.getName()) && !orgId.equals(student.getOrgId()) && userType != PtAccount.STUDENT_USER) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
      /*if((teacher!=null&&!t.getName().equals(teacher.getName())&&!orgId.equals(teacher.getOrgId())&&userType!=Account.TEACHER_USER)
          || (student!=null&&!t.getName().equals(student.getName())&&!orgId.equals(teacher.getOrgId())&&userType!=Account.STUDENT_USER)){
        return true;
      }else {
        return false;
      }*/
        }
    }

    @Override
    public PtAccount getByAccountName(String accountName) {
        PtAccount account = new PtAccount();
        account.setAccount(accountName);
        account.setDeleted(false);
        return accountMapper.selectOne(account);
    }

    @Override
    public Integer resetPassword(String accountId) {
        PtAccount account = accountMapper.selectById(accountId);
        String salt = "";
        String password = EncryptPassword.encryptPassword(Const.DEFAULT_PWD);
        account.setPassword(password);
        account.setSalt(salt);
        Integer count = accountMapper.updateAllColumnById(account);
        return count;
    }

    @Override
    public Result updatePwd(PtAccount account) {
        PtAccount currentUser=ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        Result rs = new Result();
        String newpsd = account.getPassword();
        rs.setCode(Result.SUCCESS);
        rs.setMsg("修改成功！");
        try {
            if (newpsd != null && newpsd.equals(account.getFlags())) {
                assert currentUser != null;
                account.setPassword(EncryptPassword.encryptPassword(newpsd));
                account.setId(currentUser.getId());
                String oldPwd = EncryptPassword.encryptPassword(account.getFlago());
                if (account.update(" password= '" + oldPwd+"' and id= '"+account.getId()+"'", account)) {
                    rs.setCode(Result.FAIL);
                    rs.setMsg("原密码输入错误！");
                } else {
                    currentUser.setPassword(account.getPassword());
                    ShiroKit.setSessionAttr(SessionKey.CURRENT_USER,currentUser);
                }
                sendAccountModifyMessage(currentUser.getId());
            } else {
                rs.setCode(Result.FAIL);
                rs.setMsg("两次密码输入不一致！");
            }
        } catch (Exception e) {
            rs.setCode(Result.FAIL);
            rs.setMsg("服务器异常！");
        }
        return rs;
    }

    @Override
    public void updateEnable(PtAccount account) {
        if (account != null) {
            account.setEnable(account.getEnable());
            accountMapper.updateById(account);
            PtAccount acc = accountMapper.selectById(account.getId());
            switch (SysRole.getRoleById(acc.getUserType())) {
                case AREAMANAGER:
                case AREAWORKER:
                    EduEmployee e = new EduEmployee();
                    e.setId(acc.getId());
                    e.setEnable(account.getEnable());
                    eduEmpMapper.updateById(e);
                    break;
                case TEACHER:
                case SCHMANAGER:
                case SCHWORKER:
                    Teacher t = new Teacher();
                    t.setId(acc.getId());
                    t.setEnable(account.getEnable());
                    teacherMapper.updateById(t);
                    break;
                case STUDENT:
                    Student s = new Student();
                    s.setId(acc.getId());
                    s.setEnable(account.getEnable());
                    studentMapper.updateById(s);
                    break;
                default:
                    People p = new People();
                    p.setId(acc.getId());
                    p.setEnable(account.getEnable());
                    peopleMapper.updateById(p);
                    break;
            }
             sendAccountModifyMessage(acc.getId());
        }
    }

    @Override
    public void sendAccountModifyMessage(String uid) {
        PtAccount acc = accountMapper.selectById(uid);
        if (acc != null) {
            AccountVo accountVo = new AccountVo();
            BeanUtils.copyProperties(acc, accountVo);
            UserMessage userMessege = new UserMessage();
            userMessege.setMessageType(MessageTypes.ACCOUNT_MODIFY.name());
            userMessege.setAccountVo(accountVo);
            jmsService.sendMessage(userMessege);

        }
    }

    @Override
    public String exportUserRole(String id) {
        String userRoleStr = "";
       EntityWrapper<PtUserRole> userRole = new EntityWrapper<>();
        userRole.eq("account_id",id);
        List<PtUserRole> findAll =ptUserRoleMapper .selectList(userRole);
        if (findAll.size() > 0) {
            for (PtUserRole ur : findAll) {
                if (ur.getRoleId() != null) {
                    String gradeName = "";
                    String subjectName = "";
                    PtRole role = ptRoleMapper.selectById(ur.getRoleId());
                    if (ur.getGradeId() != null && ur.getGradeId() != 0) {
                        gradeName = MetaUtils.getMeta(ur.getGradeId()).getName();
                    }
                    if (ur.getSubjectId() != null && ur.getSubjectId() != 0) {
                        subjectName = MetaUtils.getMeta(ur.getSubjectId()).getName();
                    }
                    if (role != null) {
                        userRoleStr += gradeName + subjectName + role.getRoleName() + ",";
                    }
                }
            }
        } else {
            userRoleStr = "无";
        }
        return userRoleStr;
    }

    @Override
    public PtAccount findAccountWithInfo(String accountId) {
        if (accountId == null) {
            return null;
        }
        PtAccount account = selectById(accountId);
        if (account != null && account.getUserInfo() == null) {
            CommUser userInfo = null;
            switch (Objects.requireNonNull(SysRole.getRoleById(account.getUserType()))) {
                case AREAWORKER:
                case AREAMANAGER:
                    userInfo = eduEmpMapper.getById(account.getId());
                    break;
                case STUDENT:
                    userInfo = studentMapper.getById(account.getId());
                    break;
                case TEACHER:
                case SCHWORKER:
                case SCHMANAGER:
                    userInfo = teacherMapper.getById(account.getId());
                    break;
                default:
                    userInfo = peopleMapper.getById(account.getId());
                    break;
            }
            account.setUserInfo(userInfo);

        }
        return account;
    }

    @Override
    public void deleteUser(String id, Boolean deleted) {
        if (deleted != null && deleted) {
            PtAccount acc = accountMapper.selectById(id);
            clearUserById(id);
            // 发送消息
            UserMessage userMessege = new UserMessage();
            AccountVo accountVo = new AccountVo();
            accountVo.setAccount(acc.getAccount());
            accountVo.setId(id);
            userMessege.setAccountVo(accountVo);
            userMessege.setMessageType(MessageTypes.USER_DELETE.name());
            userMessege.setContent(id);
            jmsService.sendMessage(userMessege);
            Teacher teacher = teacherMapper.selectById(id);
            if (null != teacher) {
                teacher.setSchoolCard("");
                teacherMapper.updateById(teacher);
            }
            Student student = studentMapper.selectById(id);
            if (null != student) {
                student.setStudentCardId("");
                student.setStudentCode("");
                studentMapper.updateById(student);
            }
        } else {
            if (StringUtils.isNotEmpty(id)) {
                PtAccount acc = selectById(id);
                acc.setEnable(false);
                acc.setDeleted(true);
                acc.setCellphone("");
                acc.setEmail("");
                updateById(acc);
                sendUserMessege(MessageTypes.USER_UPDATE.name(), id);
                Teacher teacher = teacherMapper.selectById(id);
                if (null != teacher) {
                    teacher.setSchoolCard("");
                    teacherMapper.updateById(teacher);
                }
                Student student = studentMapper.selectById(id);
                if (null != student) {
                    student.setStudentCardId("");
                    student.setStudentCode("");
                    studentMapper.updateById(student);
                }
            }
        }
    }

    @Override
    public Result updateByUserType(PtAccount ptAccount) {
        PtAccount oldUser = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        result.setMsg("修改成功！");
        if (ptAccount.getCellphone() != null
                && ptAccount.getCellphone().matches(PtAccount.MOBILE_PHONE_NUMBER_PATTERN)) { // 验证手机
            PtAccount model = new PtAccount();// 禁用不可恢复
            model.setDeleted(false);
            model.setEnable(true);
            model.setCellphone(ptAccount.getCellphone());
            model = accountMapper.selectOne(model);
            if (model == null) {
                ptAccount.setCellphone(ptAccount.getCellphone());
                result.setMsg("修改成功！");
            } else {
                ptAccount.setCellphone("");
                result.setCode(Result.FAIL);
                result.setMsg("手机号已被占用");
            }
        }
        accountMapper.updateById(ptAccount);
        CommUser commUser = new CommUser();
        commUser.setId(ptAccount.getId());
        commUser.setName(ptAccount.getName());
        commUser.setTelephone(ptAccount.getTelephone());
        commUser.setBirthday(ptAccount.getBirthday());
        commUser.setEmail(ptAccount.getEmail());
        commUser.setPhoto(ptAccount.getPhoto());
        commUser.setCellphone(ptAccount.getCellphone());
        commUser.setSex(ptAccount.getSex());
        switch (Objects.requireNonNull(SysRole.getRoleById(ptAccount.getUserType()))) {
            case AREAWORKER:
            case AREAMANAGER:
                EduEmployee eduEmployee = eduEmpMapper.selectById(commUser.getId());
                if (StringUtils.isNoneBlank(commUser.getPhoto()) && !eduEmployee.getPhoto().equals(commUser.getPhoto())) {
                    resourcesService.deleteResources(eduEmployee.getPhoto());
                    resourcesService.updateTmptResources(commUser.getPhoto());
                    oldUser.getUserInfo().setPhoto(commUser.getPhoto());
                }
                BeanUtils.copyProperties(commUser, eduEmployee);
                eduEmpMapper.updateById(eduEmployee);
                break;
            case STUDENT:
                Student student = studentMapper.selectById(commUser.getId());
                if (StringUtils.isNoneBlank(commUser.getPhoto()) && !student.getPhoto().equals(commUser.getPhoto())) {
                    resourcesService.deleteResources(student.getPhoto());
                    resourcesService.updateTmptResources(commUser.getPhoto());
                    oldUser.getUserInfo().setPhoto(commUser.getPhoto());
                }
                BeanUtils.copyProperties(commUser, student);
                studentMapper.updateById(student);
                break;
            case TEACHER:
            case SCHWORKER:
            case SCHMANAGER:
                Teacher teacher = teacherMapper.selectById(commUser.getId());
                if (StringUtils.isNoneBlank(commUser.getPhoto()) && !teacher.getPhoto().equals(commUser.getPhoto())) {
                    resourcesService.deleteResources(teacher.getPhoto());
                    resourcesService.updateTmptResources(commUser.getPhoto());
                    oldUser.getUserInfo().setPhoto(commUser.getPhoto());
                }
                BeanUtils.copyProperties(commUser, teacher);
                teacherMapper.updateById(teacher);
                break;
            default:
                People people = peopleMapper.selectById(commUser.getId());
                if (StringUtils.isNoneBlank(commUser.getPhoto()) && !people.getPhoto().equals(commUser.getPhoto())) {
                    resourcesService.deleteResources(people.getPhoto());
                    resourcesService.updateTmptResources(commUser.getPhoto());
                    oldUser.getUserInfo().setPhoto(commUser.getPhoto());
                }

                BeanUtils.copyProperties(commUser, people);
                peopleMapper.updateById(people);
                break;
        }
        ShiroKit.setSessionAttr(SessionKey.CURRENT_USER, oldUser);
        return result;
    }

    @Override
    public void sendUserMessege(String messageType, String id) {
        if (StringUtils.isNotEmpty(id)) {
            PtAccount acc = accountMapper.selectById(id);
            UserMessage userMessege = new UserMessage();
            userMessege.setMessageType(messageType);
            String name = "";
            if (acc != null) {
                CommUserVo commUserVo = new CommUserVo();
                switch (SysRole.getRoleById(acc.getUserType())) {
                    case AREAMANAGER:
                    case AREAWORKER:
                        name = eduEmpMapper.selectById(id).getName();
                        BeanUtils.copyProperties(eduEmpMapper.selectById(id), commUserVo);
                        break;
                    case TEACHER:
                    case SCHMANAGER:
                    case SCHWORKER:
                        name = teacherMapper.selectById(id).getName();
                        BeanUtils.copyProperties(teacherMapper.selectById(id), commUserVo);
                        break;
                    case STUDENT:
                        name = studentMapper.selectById(id).getName();
                        BeanUtils.copyProperties(studentMapper.selectById(id), commUserVo);
                        break;
                    default:
                        name = peopleMapper.selectById(id).getName();
                        BeanUtils.copyProperties(peopleMapper.selectById(id), commUserVo);
                        break;
                }

                AccountVo accountVo = new AccountVo();
                BeanUtils.copyProperties(acc, accountVo);
                accountVo.setName(name);
                userMessege.setAccountVo(accountVo);
                userMessege.setCommUserVo(commUserVo);
                jmsService.sendMessage(userMessege);
            }
        }
    }

    public void clearUserById(String uid) {
        if (!"".equals(uid)) {
            PtAccount account = selectById(uid);
            if (account == null) {
                return;
            }
            super.deleteById(uid);
            switch (SysRole.getRoleById(account.getUserType())) {
                case AREAWORKER:
                case AREAMANAGER:
                    eduEmpMapper.deleteById(uid);
                    break;
                case STUDENT:
                    studentMapper.deleteById(uid);
                    break;
                case TEACHER:
                case SCHWORKER:
                case SCHMANAGER:
                    teacherMapper.deleteById(uid);
                    break;
                default:
                    peopleMapper.deleteById(uid);
                    break;
            }
        }

    }
    @Override
    public void sendUserRoleMessege(String messageType, PtUserRole ur) {
        if (ur != null) {
            UserRoleMessage userMessege = new UserRoleMessage();
            UserRoleVo userRoleVo = new UserRoleVo();
            BeanUtils.copyProperties(ur, userRoleVo);
            userMessege.setMessageType(messageType);
            userMessege.setUserRole(userRoleVo);
            jmsService.sendMessage(userMessege);
        }
    }

    @Override
    public void changeAccountEnableStatus(List<String> userIds, boolean enable, String disableReason) {
              accountMapper.changeAccountEnableStatus(userIds,enable,disableReason);
    }
}
